#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$
import logging
from  aggmon.direct_rpc_server import DirectRPCServer
from aggmon.aggmon_component import Component


__all__ = ["Channel", "ChannelComponent"]


class Channel(object):
    __amqp_channels = {}    
    __local_channels = {}

    def __init__( self ):
        pass
    
    @staticmethod
    def cleanup():
        for key, channel in Channel.__amqp_channels.items():
            channel.cleanup()
            del Channel.__amqp_channels[key]
        for key, channel in Channel.__local_channels.items():
            channel.cleanup()
            del Channel.__local_channels[key]

    @staticmethod
    def channel_stats():
        out = []
        for channel in Channel.__local_channels.values():
            out.append( channel.stats() )
        for channel in Channel.__amqp_channels.values():
            out.append( channel.stats() )
        return out

    @staticmethod
    def open( url, **kwds ):
        #print "channel.open('%s')" % url
        scheme, rest = url.split( "://" )
        _ignore, channel_name = rest.split( "/", 1 )            

        if scheme == "amqp":
            from aggmon.channels.amqp import AMQPChannel

            try:
                return Channel.__amqp_channels[url]
            except KeyError:
                amqp_channel = AMQPChannel( url, **kwds )
                Channel.__amqp_channels[url] = amqp_channel
                return amqp_channel
        
        elif scheme == "pika":
            from aggmon.channels.amqp import PIKAChannel

            try:
                return Channel.__amqp_channels[url]
            except KeyError:
                amqp_channel = PIKAChannel( url, **kwds )
                Channel.__amqp_channels[url] = amqp_channel
                return amqp_channel
        
        elif scheme == "local":
            from aggmon.channels.local import LocalChannel
                        
            try: 
                return Channel.__local_channels[url]
            except KeyError:                
                local_channel = LocalChannel( url, **kwds )
                Channel.__local_channels[url] = local_channel
                return local_channel

        else:
            raise ValueError, "unknown channel URL scheme: " + scheme            

    def publish( self, topic, message ):
        raise NotImplementedError
    
    def subscribe( self, topic, notify_callback ):
        raise NotImplementedError


DirectRPCServer.register_rpc( "channel_stats", Channel.channel_stats )


class ChannelComponent(Component):
    def __init__( self, url, name=None, **kwds ):
        # must have a name and end with "Channel"
        assert name is not None, "'name' must be passed as argument to ChannelComponents!"
        Component.__init__( self, args=[url], name=name, **kwds )
        self.allowed_kwds = ["durable"]

    def instantiate( self, *args, **kwds ):
        # lose the reference to any previous instance
        self.instance = None
        try:
            logging.debug( "instantiating: %s" % self.name )
            self.instance = Channel.open( *args, **kwds )
        except Exception, e:
            raise e

    def start( self, **kwds ):
        "Equivalent to opening the channel."
        k = {}
        for key, val in self.cmd["kwds"].items():
            k[key] = val 
        for key, val in kwds.items():
            if key in self.allowed_kwds:
                k[key] = val
        try:
            self.instantiate( *self.cmd["args"], **k )
        except Exception, e:
            self.state = Component.STOPPED
            logging.error( "Failed starting: %s, Exception: %s" % (self.name, str(e)) )
            raise e
        else:
            self.state = Component.RUNNING

    def stop( self ):
        # just forget the current instance?
        self.instance.cleanup()
        self.instance = None
        self.state = Component.STOPPED
